package org.yy.mdns;

import android.net.nsd.NsdManager;
import android.net.nsd.NsdServiceInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

public class ServerActivity extends AppCompatActivity {
    private static final String TAG = "ServerActivity";
    private NsdManager mNsdManager = null;
    private NsdManager.RegistrationListener mRegistrationListener;

    private final int CHAT_PORT = 6613;
    private Thread udpListenerThread;
    private boolean running = false;
    private DatagramSocket socket;
    private DatagramPacket packet;
    private final int BUFFER_SIZE = 1024*6;
    private byte[] buffer = new byte[BUFFER_SIZE];

    private TextView serverTV, msgTV;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_server);
        serverTV = findViewById(R.id.tv_server_state);
        msgTV = findViewById(R.id.tv_msg_receive);
        mRegistrationListener = new NsdManager.RegistrationListener() {
            @Override
            public void onRegistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
                Log.i(TAG,"onRegistrationFailed ");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        serverTV.setText("nsd服务：注册失败");
                    }
                });
            }

            @Override
            public void onUnregistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
                Log.i(TAG,"onUnregistrationFailed ");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        serverTV.setText("nsd服务：取消注册失败");

                    }
                });

            }

            @Override
            public void onServiceRegistered(NsdServiceInfo serviceInfo) {
                Log.i(TAG,"onServiceRegistered ");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        serverTV.setText("nsd服务：注册成功");
                    }
                });
            }

            @Override
            public void onServiceUnregistered(NsdServiceInfo serviceInfo) {
                Log.i(TAG,"onServiceUnregistered ");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        serverTV.setText("nsd服务：取消注册成功");
                    }
                });
            }
        };
        mNsdManager = (NsdManager) getSystemService(NSD_SERVICE);
        NsdServiceInfo serviceInfo = new NsdServiceInfo();
        serviceInfo.setServiceName("test");
        serviceInfo.setPort(CHAT_PORT);
        serviceInfo.setServiceType("_test._udp.");//客户端发现服务器是需要对应的这个Type字符串
        mNsdManager.registerService(serviceInfo, NsdManager.PROTOCOL_DNS_SD, mRegistrationListener);
        startUdpListener();
    }


    private void startUdpListener(){
        if(running){
            return;
        }
        try {
            socket = new DatagramSocket(CHAT_PORT);
            packet = new DatagramPacket(buffer,BUFFER_SIZE);
        } catch (SocketException e) {
            e.printStackTrace();
            return;
        }

        udpListenerThread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (running){
                    try {
                        socket.receive(packet);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if (packet == null || packet.getLength() == 0) {
                        Log.e(TAG, "无法接收UDP数据或者接收到的UDP数据为空");
                        continue;
                    }

                    final String strReceive = new String(packet.getData(), 0, packet.getLength());
                    final String ip = packet.getAddress().getHostAddress();
                    final int port = packet.getPort();
                    Log.d(TAG, strReceive + " from " + ip + ":" + port);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            msgTV.setText("收到来自"+ip+":"+port+"的消息："+strReceive);
                        }
                    });
                    sendUdpMsg(ip,port,"received you message:"+strReceive);
                }
            }
        });
        running = true;
        udpListenerThread.start();
    }

    private void sendUdpMsg(String ip,int port,String message){
        InetAddress targetAddress = null;
        try {
            targetAddress = InetAddress.getByName(ip);
            DatagramPacket packet = new DatagramPacket(message.getBytes(), message.length(), targetAddress, port);
            socket.send(packet);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void stopUdpListener(){
        if(!running){
            return;
        }
        running = false;
        udpListenerThread.interrupt();
        udpListenerThread = null;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopNSDServer();
        stopUdpListener();
    }

    public void stopNSDServer() {
        mNsdManager.unregisterService(mRegistrationListener);
    }

}
